﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Engine.Cameras;
using Engine.Debug;
using Engine.Helpers;


namespace Engine.Graphics
{
    public class MeshEntity : DrawableEntity
    {
        protected ModelMesh mesh;
        public ModelMesh Mesh { get { return mesh; } }

        public MeshEntity(Entity parent, ModelMesh mesh, Matrix offsetTransform)
            : base(parent)
        {
            this.mesh = mesh;
            this.offset = offsetTransform;

            try
            {
                if (mesh.Tag != null)
                {
                    BoundingBox = (BoundingBox)mesh.Tag;
                }
            }
            catch
            {
                BoundingBox = BoundingBox.CreateFromSphere(mesh.BoundingSphere);
            }
            BoundingSphere = mesh.BoundingSphere;
        }

        public override void Draw(GameTime gameTime)
        {
            DebugShapeRenderer.AddBoundingBox(BoundingBox.Transform(this.World), Color.Yellow);
            foreach (var meshPart in mesh.MeshParts)
            {
                Effect effect = meshPart.Effect;
                IEffectMatrices effectMatrices = effect as IEffectMatrices;

                if (effectMatrices != null)
                {
                    effectMatrices.World = World;
                    effectMatrices.View = Camera.ActiveCamera.View;
                    effectMatrices.Projection = Camera.ActiveCamera.Projection;
                }

                foreach (var pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();
                    GraphicsDevice device = effect.GraphicsDevice;
                    device.SetVertexBuffer(meshPart.VertexBuffer, meshPart.VertexOffset);
                    device.Indices = meshPart.IndexBuffer;

                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 
                        0,
                        0, 
                        meshPart.NumVertices, 
                        meshPart.StartIndex, 
                        meshPart.PrimitiveCount);
                }

            }
            base.Draw(gameTime);
        }
    }
}
